#include "datetime_period.hpp"
#include <cctype>

using namespace boost::posix_time;
using namespace boost::gregorian;


date const date_input_string::to_date(std::string const& s, char const* fmt)
{

	std::string format(fmt);

	if(format == "%d/%m/%Y")
	{		
		return from_it_string(s, '/');
	}

	boost::gregorian::date date_null(boost::gregorian::not_a_date_time);
	return date_null;
}

bool date_input_string::is_feasible_string(std::string const& str, char _sep)
{
	bool is_feasible(true);
	unsigned short remain_separator(2); // if and only if there are two char separators in string
	std::locale loc;

	for(unsigned short j=0; is_feasible && j < str.length(); j++)
	{
		if (str[j] == _sep)
		{ 
			remain_separator--; continue;
		}
		
		if(!isspace(str[j]))
		{
			is_feasible &= isdigit(str[j], loc);
		}
	}
	
	is_feasible &= !remain_separator;

	return is_feasible;
}

date const date_input_string::from_it_string(std::string const& s, char _sep)
{
	std::string str(s);

	if(is_feasible_string(s, _sep))
        {
                for(std::string::size_type _size_type=s.find_first_of(_sep); _size_type != std::string::npos; )
                {
                        str[_size_type] = '-';  
                        _size_type = s.find_first_of(_sep, _size_type+1);
                }

                return boost::gregorian::from_uk_string(str);
        }

        boost::gregorian::date date_null(boost::gregorian::not_a_date_time);
        return date_null;
}


